package com.example.demo.util;

import com.example.demo.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @BelongsProject: springboot-demo
 * @BelongsPackage: com.example.demo.util
 * @Author: yanhongwei
 * @CreateTime: 2022-04-07 16:54
 * @Description: //登录拦截器的实现
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    /**
     * @description: 在请求之前进行调用（controller方法调用之前）
     * @author: yanhongwei
     * @date: 2022/4/7 16:55
 * @param: request
 * @param: response
 * @param: handler
 * @return: boolean
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了拦截器的preHandle方法");
        try {
            HttpSession session = request.getSession();
            //统一拦截（查询当前的存session是否在user，这里的user每次登录成功后自动写入session）
            User user = (User) session.getAttribute("user");
            if (user != null) {
                return true;
            }
            response.sendRedirect(request.getContextPath() + "login");
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
        //false: 拦截器执行到此将不会继续操作
        //true: 继续执行后面的操作
    }

    //请求处理之后进行调用，但是在试图被渲染之前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行了拦截器的postHandle方法");
    }

    //整个请求结束后被调用，也就是在dispatchservlet渲染了对应的视图之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("执行了拦截器的afterCompletion方法");
    }
}
